package rocketmq;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.*;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * mq消费者
 * Created by Administrator on 2018/7/2.
 */
public class Consumer {

    public static void main(String[] args) {
        //消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_name4");
        //设置nameServer地址
        consumer.setNamesrvAddr("192.168.1.103:9876");
        //设置从队列的哪个位置消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        try {
            //订阅主题
            consumer.subscribe("topic_ums2", "tag_register || TagC || TagD");
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        /*
        注册消息监听器
        MessageListenerOrderly : 顺序消费,同一时间只有一个线程会消费同一个队列(队列而不是topic)
        MessageListenerConcurrently : 即时消费,并发的进行消费
         */
        /*consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                //设置自动提交
                consumeOrderlyContext.setAutoCommit(true);
                for (MessageExt messageExt : list){
                    try {
                        System.out.println(new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });*/
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list){
                    try {
                        System.out.println(Thread.currentThread()+" MessageListenerConcurrently "+new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.start();
            System.out.println("消费者启动");
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
